package timing.aframe4l.myandroidthings;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.nio.ByteBuffer;

/**
 * Skeleton of an Android Things activity.
 * <p>
 * Android Things peripheral APIs are accessible through the class
 * PeripheralManagerService. For example, the snippet below will open a GPIO pin and
 * set it to HIGH:
 * <p>
 * <pre>{@code
 * PeripheralManagerService service = new PeripheralManagerService();
 * mLedGpio = service.openGpio("BCM6");
 * mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
 * mLedGpio.setValue(true);
 * }</pre>
 * <p>
 * For more complex peripherals, look for an existing user-space driver, or implement one if none
 * is available.
 *
 * @see <a href="https://github.com/androidthings/contrib-drivers#readme">https://github.com/androidthings/contrib-drivers#readme</a>
 */
public class HomeActivity extends Activity {
    private Button button;
    private ImageView imageView;
    /**
     * A Handler for running tasks in the background.
     */
    private Handler mCameraHandler;
    /**
     * An additional thread for running tasks that shouldn't block the UI.
     */
    private HandlerThread mCameraThread;
    /**
     * Camera capture device wrapper
     */
    private DoorbellCamera mCamera;

    private Bitmap imageMap;

    private Handler handler=null;

    private MediaPlayer mMediaplayer = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
//        PeripheralManagerService service = new PeripheralManagerService();
//        Log.d(TAG, "Available GPIO: " + service.getGpioList());
        button = findViewById(R.id.button);
        imageView = findViewById(R.id.imageView);
        mMediaplayer=MediaPlayer.create(this,R.raw.dingdong);
        mMediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                button.setEnabled(Boolean.TRUE);
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                button.setEnabled(Boolean.FALSE);
                Toast.makeText(HomeActivity.this, "门铃响了", Toast.LENGTH_LONG).show();
                mCamera.takePicture();
                mMediaplayer.start();
            }
        });
        // Creates new handlers and associaFted threads for camera and networking operations.
        mCameraThread = new HandlerThread("CameraBackground");
        mCameraThread.start();
        handler= new Handler();
        mCameraHandler = new Handler(mCameraThread.getLooper());

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    1);

        mCamera = DoorbellCamera.getInstance();
        mCamera.initializeCamera(this, mCameraHandler, mOnImageAvailableListener);
    }

    // Callback to receive captured camera image data
    private ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
        @Override
        public void onImageAvailable(ImageReader reader) {
            // Get the raw image bytes
            Image image = reader.acquireLatestImage();
            if (image != null) {
                ByteBuffer imageBuf = image.getPlanes()[0].getBuffer();
                final byte[] imageBytes = new byte[imageBuf.remaining()];
                imageBuf.get(imageBytes);
                image.close();
                imageMap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                new Thread() {
                    public void run() {
                        handler.post(runnableUi);
                    }
                }.start();

            }
        }
    };

    // 构建Runnable对象，在runnable中更 新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面
            if (imageMap != null)
                imageView.setImageBitmap(imageMap);
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCameraThread.quitSafely();
        mCamera.shutDown();
        mMediaplayer.release();
    }
}
